package com.cg;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author cheyinbo
 * @description TODO
 * @date 2021/8/18 11:59
 */
public class JDKProxy02 {
    public static void main(String[] args) {
        JDKTeacherDao02 jdkTeacherDao02 = new JDKTeacherDaoImpl02();
        ProxyFactory02 proxyFactory02 = new ProxyFactory02(jdkTeacherDao02);
        JDKTeacherDao02 proxyInstance = (JDKTeacherDao02) proxyFactory02.newInstance();
        System.out.println(proxyInstance.getClass());
        System.out.println(proxyInstance.teach("张老师"));
    }
}

interface JDKTeacherDao02 {

    String teach(String teacherName);
}

class JDKTeacherDaoImpl02 implements JDKTeacherDao02 {

    @Override
    public String teach(String teacherName) {
        return teacherName + "正在教课...";
    }
}

class ProxyFactory02 implements InvocationHandler {

    private final Object target;

    public ProxyFactory02(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        System.out.println("代理开始");
        Object invoke = method.invoke(target, objects);
        System.out.println("代理结束");
        return invoke;
    }

    public Object newInstance() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }
}